<?php

App::uses('AppModel', 'Model');

class Product extends AppModel {
        
    public $belongsTo = array('Group');
    
    public function beforeSave($options=array()) {
        if ($upload = $this->getImageForUpload()) {
            $data = $this->data['Product'];
            if (! empty($data['image'])) {
                $this->deleteImage($data['group_id'], $data['image']);
            }
            
            $data['image'] = $upload['name'];
            $this->set($data);
        }
        
        return parent::beforeSave($options);
    }
    
    public function afterSave($created, $options=array()) {
        if ($upload = $this->getImageForUpload()) {
            $data = $this->data;
            $dest = IMG_DIR . implode(DS, array('products', $data['Product']['group_id'], $upload['name']));
            
            $dest_dir = dirname($dest);
            if (!is_dir($dest_dir)) {
                mkdir($dest_dir, 0775);
            }
            @move_uploaded_file($upload['tmp_name'], $dest);
        }
        
        return parent::afterSave($created, $options);
    }
    
    public function beforeDelete($cascade = true) {
        if (! $this->data) {
            $this->data = $this->findById($this->id);
        }
        
        return parent::beforeDelete($cascade);
    }
    
    public function afterDelete() {
        $image   = @$this->data['Product']['image'];
        if ($image) {
            $groupId = $this->data['Group']['id'];
            $this->deleteImage($groupId, $image);
        }
        
        return parent::afterDelete();
    }
    
    private function getImageForUpload() {
        $ret = false;
        $data   = $this->data['Product'];
        $upload = $data['image_upload'];
        if (! $upload['error']) {
            $ret = $upload;
        }
    
        return $ret;
    }
    
    private function deleteImage($groupId, $image) {
        $path = implode(DS, array('products', $groupId, $image));
        @unlink(IMG_DIR . $path);
    }
}